<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Category Search</title>

<%
String category = request.getParameter("c");
%>
<jsp:include page="header.html"></jsp:include>
</head>
<body>
<div class="searchSection">
	<div class="selector" style="float: left;">	</div>
	<div class="query">
		<input type="text" width="100" id="query" ><input type="button" id="search" value="search">
	</div>
</div>
<div class="resultSection" id="result"></div>
<div class="footer">
		<button name="home" onclick="goHome();">home</button>
	</div>
</body>
<script type="text/javascript">
var category = <%= category %>;
var pathParam = "<%= category %>";

function load()
{
	console.log("at ready, category is " + pathParam);
	var div = $(".selector");
	
	var select = document.createElement("select");
	select.setAttribute("id", pathParam);
	
	for(var entry in category)
	{
		var txt = document.createTextNode(entry);
		
		var option = document.createElement("option");
		
		option.appendChild(txt);
		select.appendChild(option);
	}
	
	div.append(select);
}

$(document).ready(load);

function search() 
{
	var query =  $("#query").val();
	var selectQ = "#" + pathParam + " option:selected";
	var select =  $(selectQ);
	
	var url = "rest/search/" + pathParam + "/item"; 
	$.ajax({
		url : url,
		type : "get",
		beforeSend : function(xhr)
		{
			xhr.setRequestHeader( "encoding", "UTF-8");
			xhr.setRequestHeader( pathParam, select.text() ); // selector
			xhr.setRequestHeader( "query",  encodeURI(query));
			console.log("header param (" + pathParam + ", " + select.text() +"), (query, " + query + ")");
		},
		dataType : "json",
		success : function(data)
		{
			if(data == null) 
			{
				console.log("null data");
				var resultArea = document.getElementById("result");
				var txt = document.createTextNode("No data.");
				resultArea.appendChild(txt);
			}
			else
			{
				console.log(data.product.length);
				
				if(data.product.length > 1)
				{
					for(var i = 0; i < data.product.length; ++i)
					{
						var entry = data.product[i];
						
						display(entry);
					}
				}else
				{
					display(data.product);
				}
			}
		}
	}); 
}

$("input[value ='search']").click(search);
$("#query").keydown(function (evt)
		{
			if(evt.keyCode == 13)
			{
				$("input[value ='search']").trigger('click');
			} 
		});

</script>
</html>